package com.bst.etl.batch.reader;

import com.bst.common.utils.StringUtils;
import com.bst.common.utils.sql.EtlUtil;
import com.bst.etl.batch.url.UrlInvoke;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Scope("prototype")
public class InterReader implements ItemReader<Map<String,Object>> {

    private List<Map<String,Object>> dataList;

    private Integer num=0;

    /*private String assessToken;
    @Value("#{jobParameters['url']}")
    private String url;
    @Value("#{jobParameters['euReq']}")
    private String euReq;
    @Value("#{jobParameters['querySql']}")
    private String urlParam;
    @Value("#{jobParameters['inter']}")
    private String inter="";*/

    JobParameters parameters;

    @BeforeStep
    public void beforeStep(final StepExecution stepExecution) {
        parameters = stepExecution.getJobParameters();
        dataList = initIalize();
        num=0;
    }

    @Override
    public Map<String, Object> read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
        Map<String, Object> map = null;
        if (dataList!=null && num < dataList.size()) {
            map = dataList.get(num);
        }
        num++;
        return map;
    }

    private List<Map<String,Object>> initIalize() {
        try {
            UrlInvoke invoke = new UrlInvoke();
            Class urlClass = invoke.getClass();
            String inter=parameters.getString("inter"),url=parameters.getString("url"),
                    urlParam=parameters.getString("querySql");
            if(StringUtils.isEmpty(inter)) {
                inter = "vteGetInvoke";
            }
            Date beginDate = parameters.getDate("DT_DAY_BEGIN");
            Date endDate = parameters.getDate("DT_DAY_END");
            urlParam = EtlUtil.buildSql(urlParam,beginDate,endDate,"");
            urlParam = urlParam.replaceAll("'","");
            Method method = urlClass.getMethod(inter,String.class,String.class);
            List<Map<String,Object>> list = (List<Map<String,Object>>)method.invoke(invoke,url,urlParam);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
